package com.fyakm.daodejing.stock.util;

import com.fyakm.daodejing.stock.domain.StockHistoryItem;
import com.opencsv.CSVReader;

import java.io.FileReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CsvReader {
    // 读取股票历史数据
    public static List<StockHistoryItem> readStockHistoryFromCsv(String filePath) {
        List<StockHistoryItem> historyList = new ArrayList<>();
        try (CSVReader reader = new CSVReader(new FileReader(filePath))) {
            List<String[]> records = reader.readAll();
            // 跳过表头行
            records.remove(0);
            for (String[] record : records) {
                StockHistoryItem history = new StockHistoryItem();
                String dateStr = record[0];

                // 將日期字符串轉換為Date類型(格式是yyyy-MM-dd)
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = sdf.parse(dateStr);
                 history.setDate(date);
                history.setCode(record[1]);
                history.setOpen(BigDecimal.valueOf(Double.parseDouble(record[2])));
                history.setHigh(BigDecimal.valueOf(Double.parseDouble(record[3])));
                history.setLow(BigDecimal.valueOf(Double.parseDouble(record[4])));
                history.setClose(BigDecimal.valueOf(Double.parseDouble(record[5])));
                history.setPreclose(BigDecimal.valueOf(Double.parseDouble(record[6])));
                history.setVolume(BigDecimal.valueOf(Double.parseDouble(record[7])));
                history.setAmount(BigDecimal.valueOf(Double.parseDouble(record[8])));
                history.setPctChg(BigDecimal.valueOf(Double.parseDouble(record[9])));
                historyList.add(history);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return historyList;
    }
}